﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace Middlerware.Sample
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class RequestIdInResponseMiddleware:IMiddleware
    {
        private readonly IService _service;

        public RequestIdInResponseMiddleware(IService service)
        {
            _service = service;
        }

        public Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            var requestId = Guid.NewGuid().ToString("n");
            context.Response.Headers.Add("REQUESTID", requestId);

            return next(context);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class RequestId2MiddlewareExtensions
    {
        public static IApplicationBuilder UseRequestIdInResponseMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestIdInResponseMiddleware>();
        }
    }
}
